package com.edais.actions;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.RateRisesCoupons;
import com.edais.domain.User;
import com.edais.domain.UserVouchers;
import com.edais.service.RateRisesCouponsService;
import com.edais.service.UserService;
import com.edais.service.UserVouchersService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.JsonUtil;
import com.edais.util.Message;

@Controller
@RequestMapping("/userVochers")

public class UserVouchersAction {
	private static final Log logger = LogFactory.getLog(UserVouchersAction.class);
	
	@Autowired
	private UserVouchersService userVouchersService;
	
	@Autowired
	private RateRisesCouponsService rateRisesCouponsService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 我的代金券
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/myVouchers")
	public void myVouchers(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		//加排序和不加排序版本的区别标识：0-老版本，1-新版本
		if ("1".equals(paramsMap.get("vsFlag"))) {
			String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
			String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
			Integer current = 1;
			Integer pageSize = 10;//默认显示10条
			String userId = paramsMap.get("userId");//用户ID
			String loanId = paramsMap.get("loanId");//产品ID
			String investmentAmount = paramsMap.get("investmentAmount");
			String sortType = paramsMap.get("sortType");
			String remanPeriods = paramsMap.get("remanPeriods");
			String productType = paramsMap.get("productType");
			try{
				if (StringUtils.isBlank(userId)) {
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

					// 处理返回结果
					CommonUtil.responseJson(result, response);
					logger.debug("userVochers/myVouchers 传入用户ID为空");
					return;
				}
				//分页参数
				if (currentPageStr != null && !("".equals(currentPageStr))) {
					current = Integer.parseInt(currentPageStr);
				}
				if (pageSizeStr != null && !("".equals(pageSizeStr))) {
					pageSize = Integer.parseInt(pageSizeStr);
				}
				Map<String,Object> reqMap = new HashMap<String,Object>();
				reqMap.put("userId", userId);
				reqMap.put("rowBegin",(current-1)*pageSize);
				reqMap.put("rowEnd",pageSize);
				reqMap.put("current",current);
				reqMap.put("vsFlag",paramsMap.get("vsFlag"));
				if(StringUtils.isNotBlank(sortType)){
					reqMap.put("sortType",sortType);
				}
				if(StringUtils.isNotBlank(remanPeriods)){
					reqMap.put("remanPeriods",remanPeriods);
				}
				if(StringUtils.isNotBlank(productType)){
					reqMap.put("productType",productType);
				}
				
				if(StringUtils.isNotBlank(loanId)){
					reqMap.put("loanId",loanId);
				}
				if(StringUtils.isNotBlank(investmentAmount)){
					reqMap.put("investmentAmount",new BigDecimal(investmentAmount));
				}
				jsonMap = this.userVouchersService.myVouchers2(reqMap);
				// 处理返回结果
				String result = JsonUtil.getJsonStringFromMap(jsonMap);
				CommonUtil.responseJson(result, response);
			}catch (Exception e) {
				logger.error("查询我的加息券异常:" + e.getMessage());
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
		}else{
			String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
			String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
			Integer current = 1;
			Integer pageSize = 10;//默认显示10条
			String userId = paramsMap.get("userId");//用户ID
			String loanId = paramsMap.get("loanId");//产品ID
			String investmentAmount = paramsMap.get("investmentAmount");
			try{
				
				if (StringUtils.isBlank(userId)) {
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

					// 处理返回结果
					CommonUtil.responseJson(result, response);
					logger.debug("userVochers/myVouchers 传入用户ID为空");
					return;
				}
				//分页参数
				if (currentPageStr != null && !("".equals(currentPageStr))) {
					current = Integer.parseInt(currentPageStr);
				}
				if (pageSizeStr != null && !("".equals(pageSizeStr))) {
					pageSize = Integer.parseInt(pageSizeStr);
				}
				Map<String,Object> reqMap = new HashMap<String,Object>();
				reqMap.put("userId", userId);
				reqMap.put("rowBegin",(current-1)*pageSize);
				reqMap.put("rowEnd",pageSize);
				reqMap.put("current",current);
				if(StringUtils.isNotBlank(loanId)){
					reqMap.put("loanId",loanId);
				}
				if(StringUtils.isNotBlank(investmentAmount)){
					reqMap.put("investmentAmount",new BigDecimal(investmentAmount));
				}
				jsonMap = this.userVouchersService.myVouchers(reqMap);
				// 处理返回结果
				String result = JsonUtil.getJsonStringFromMap(jsonMap);
				CommonUtil.responseJson(result, response);
			}catch (Exception e) {
				logger.error("查询我的加息券异常:" + e.getMessage());
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
		}
	}
	
	/**
	 * 根据代金券ID查询相应产品
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getScatteredInfoByVoucherId")
	public void getScatteredInfoByVoucherId(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String voucherId = paramsMap.get("voucherId");//用户ID
		try{
			
			if (StringUtils.isBlank(voucherId)) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

				// 处理返回结果
				CommonUtil.responseJson(result, response);
				logger.debug("userVochers/myVouchers 传入代金券ID为空");
				return;
			}
			
			Map<String,Object> reqMap = new HashMap<String,Object>();
			reqMap.put("voucherId", voucherId);
			
			jsonMap = this.userVouchersService.getScatteredInfoByVoucherId(reqMap);
			// 处理返回结果
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		}catch (Exception e) {
			logger.error(" 根据代金券ID查询相应产品异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 获取代金券、加息券等列表
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getMyCouponsList")
	public void getMyCouponsList(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String productType = paramsMap.get("productType");//用户ID
		String remanPeriods = paramsMap.get("remanPeriods");//期数
		String userId = paramsMap.get("userId");
		Boolean remanFlag = Boolean.valueOf(paramsMap.get("remanFlag"));
		
		try{
			if (StringUtils.isBlank(productType)) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

				// 处理返回结果
				CommonUtil.responseJson(result, response);
				logger.debug("userVochers/getMyCouponsList 传入产品类型为空");
				return;
			}
			
			if (StringUtils.isBlank(userId)) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

				// 处理返回结果
				CommonUtil.responseJson(result, response);
				logger.debug("userVochers/getMyCouponsList 传入用户ID为空");
				return;
			}
			
			if(productType.equals("108")){
				if (StringUtils.isBlank(remanPeriods)) {
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

					// 处理返回结果
					CommonUtil.responseJson(result, response);
					logger.debug("userVochers/getMyCouponsList 传入产品期数为空");
					return;
				}
				
				if (remanFlag==null) {
					String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

					// 处理返回结果
					CommonUtil.responseJson(result, response);
					logger.debug("userVochers/getMyCouponsList 传入短期标标识为空");
					return;
				}
			}
			
			//获取用户信息
			User user = this.userService.getUserDetail(userId);
			Integer current = 1;
			Integer pageSize = 1000;//默认显示10条
			Map<String,Object> reqMap = new HashMap<String,Object>();
			reqMap.put("status", "0");
			reqMap.put("userId", userId);
			reqMap.put("mobile", user.getMobile());
			reqMap.put("rowBegin",(current-1)*pageSize);
			reqMap.put("rowEnd",pageSize);
			reqMap.put("current",current);
			if(productType.equals("108")){
				reqMap.put("product",remanPeriods);
			}else{
				reqMap.put("product",0);
			}
			
			List<RateRisesCoupons> rateRisesCouponsList = this.rateRisesCouponsService.queryRateRisesCouponsListByUser(reqMap);
			Integer rateRisesCouponsListCount = this.rateRisesCouponsService.queryRateRisesCouponsListByUserCount(reqMap);
			
			jsonMap.put("rateRisesCouponsList", rateRisesCouponsList);
			jsonMap.put("rateRisesCouponsListCount", rateRisesCouponsListCount);
			
			//查询代金券列表
			reqMap.put("productType", productType);
			if(productType.equals("108")){
				if(remanFlag){
					reqMap.put("remanPeriods", Integer.parseInt(remanPeriods));
				}else{
					reqMap.put("remanPeriods", Integer.parseInt(remanPeriods)*30);
				}
			}else{
				reqMap.put("remanPeriods", 0);
			}
			
			List<UserVouchers> vouchersList = this.userVouchersService.queryVouchersByParams(reqMap);
			Integer vouchersListCount = this.userVouchersService.queryVouchersByParamsCount(reqMap);
			
			jsonMap.put("vouchersList", vouchersList);
			jsonMap.put("vouchersListCount", vouchersListCount);
			
			// 处理返回结果
			String result = CommonUtil.setResultStringCn(
					jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
			CommonUtil.responseJson(result, response);
			
		}catch (Exception e) {
			logger.error("获取代金券、加息券等列表异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 根据产品ID查询代金券列表
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryVouchersByLoanId")
	public void queryVouchersByLoanId(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");//用户ID
		String loanId = paramsMap.get("loanId");//产品ID
		try{
			
			if (StringUtils.isBlank(userId)) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

				// 处理返回结果
				CommonUtil.responseJson(result, response);
				logger.debug("userVochers/queryVouchersByLoanId 传入用户ID为空");
				return;
			}
			if (StringUtils.isBlank(loanId)) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

				// 处理返回结果
				CommonUtil.responseJson(result, response);
				logger.debug("userVochers/queryVouchersByLoanId 传入产品ID为空");
				return;
			}
			Integer current = 1;
			Integer pageSize = 1000;//默认显示10条
			//分页参数
			Map<String,Object> reqMap = new HashMap<String,Object>();
			reqMap.put("userId", userId);
			reqMap.put("loanId",loanId);
			reqMap.put("rowBegin",(current-1)*pageSize);
			reqMap.put("rowEnd",pageSize);
			reqMap.put("current",current);
			
			jsonMap = this.userVouchersService.queryVouchersByLoanId(reqMap);
			// 处理返回结果
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		}catch (Exception e) {
			logger.error("根据产品ID查询代金券列表异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 查询活期代金券数量
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryVouchersCount")
	public void queryVouchersCount(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");//用户ID

		try{
			
			if (StringUtils.isBlank(userId)) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

				// 处理返回结果
				CommonUtil.responseJson(result, response);
				logger.error("userVochers/queryVouchersCount 传入用户ID为空");
				return;
			}
			
			Map<String,Object> reqMap = new HashMap<String,Object>();
			reqMap.put("userId", userId);
			reqMap.put("productType", "109");
			
			jsonMap = this.userVouchersService.queryVouchersCount(reqMap);
			// 处理返回结果
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		}catch (Exception e) {
			logger.error("根据产品ID查询代金券列表异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
}
